#include <stdio.h>

int fsize(char *FileName)//Get the size of File
{
	FILE *file;
	file = fopen(FileName, "r");
    int prev = ftell(file);
    fseek(file, 0L, SEEK_END);
    int sz = ftell(file);
    fseek(file, prev, SEEK_SET); //go back to where we were
    return sz;
}

char* GetCharF(char *FileName)// Get text in File
{	
	FILE *file;
	file = fopen(FileName, "r");

	char *DataF;

	if (file) 
	{
		int length=fsize(FileName);
		DataF = new char[length];

		int i = 0;
		while(DataF[i] != NULL)
		{
			DataF[i] = 0;
			i++;
		}

		fread(DataF, 1, length, file);
		fclose(file);
	}	
	return DataF;
	delete[] DataF;
}

void WriteF(char *DestinationFile, char *charF)// write to file
{
	FILE *file;
	file = fopen(DestinationFile, "w");
	if(file)
	{
		fprintf(file, "%s", charF);
	}
	fclose(file);
}

bool SearchStringInArray(char *SourceChar, char *FindChar, int &Position)// Search string in array
{
	int i = 0;
	int x = 0;

	while(SourceChar[Position+i] == ' ')
	{
		i++;
	}

	while(SourceChar[Position+i] != ' '&& SourceChar[Position+i] != NULL && FindChar[x] != NULL)
	{				
		if(SourceChar[Position+i] != FindChar[x])
		{
			i = 0;
			return false;
			break;
		}		
		i++;
		x++;			
	}

	Position = Position+i;
	return true;
}

char* ReplaceStringInArray(char *nameFileHeader, char *nameFileCpp)// replace string in array
{
	char *FileHeader = GetCharF(nameFileHeader);
	char *FileCpp = GetCharF(nameFileCpp);
	
	char *Data = new char [fsize(nameFileHeader) + fsize(nameFileCpp)];
	int z = 0;
	while(Data[z] != NULL)
	{
		Data[z] = 0;
		z++;
	}

	int i = 0;
	int t = 0;
	while(FileCpp[i] != NULL)
	{
		bool Find = true;
		if(FileCpp[i] == '#')
		{
			i++;
			
			Find = SearchStringInArray(FileCpp, "include", i);
			if(Find == true)
			{
				while(FileCpp[i] == ' ')
					i++;
				if(FileCpp[i] == '"')
					i++;
				else
				{
					Find = false;
				}
				int j=0;
				
				Find = SearchStringInArray(FileCpp, nameFileHeader, i);
				i++;
				while(FileCpp[i] == ' ')
					i++;
				if(FileCpp[i] != '"')
					Find = false;
				if(Find == true)
				{
					int k = 0;
					while(FileHeader[k] != NULL)
					{
						Data[t] = FileHeader[k];
						t++;
						k++;
					}
					i++;
				}
				else
				{
					while(FileCpp[i] != '#')
						i--;
					Data[t] = FileCpp[i];
					t++;
					i++;
				}
			}			
		}
		else
		{
			Data[t] = FileCpp[i];
			t++;
			i++;
		}
	}
	while(FileCpp[i] == NULL && Data[t] != NULL)
		Data[t] = 0;
	return Data;
	delete[] FileHeader;
	delete[] FileCpp;
	delete[] Data;
}